<template>
  <a-card title="作业布置" :bordered="false">
    <div class="assignment-container">
      <!-- Filter Section -->
      <div class="filter-section">
        <a-space :size="16">
          <a-select
            v-model:value="filter.phase"
            placeholder="选择阶段"
            style="width: 120px"
            allow-clear
          >
            <a-select-option 
              v-for="(name, value) in phaseMap "
              :key="value"
              :value="Number(value)"
            >
              {{ name }}
            </a-select-option>
          </a-select>

          <a-select
            v-model:value="filter.chapter"
            placeholder="选择章节"
            style="width: 180px"
            :loading="chapterLoading"
            allow-clear
          >
            <a-select-option
              v-for="chapter in chapterList"
              :key="chapter.id"
              :value="chapter.id"
            >
              {{ chapter.name }}
            </a-select-option>
          </a-select>
          <a-select
            v-model:value="filter.questionType"
            placeholder="题型"
            style="width: 120px"
            allow-clear
          >
            <a-select-option
              v-for="type in questionTypes"
              :key="type.value"
              :value="type.value"
            >
              {{ type.label }}
            </a-select-option>
          </a-select>

          <a-input
            v-model:value="filter.knowledgePoint"
            placeholder="输入知识点"
            style="width: 200px"
            allow-clear
          />
        </a-space>
          <a-button
            type="primary"
            @click="showAssignmentModal"
            :disabled="selectedQuestions.length === 0"
          >
            布置作业 ({{ selectedQuestions.length }})
          </a-button>
      </div>

      <!-- AI Analysis Modal -->
    <a-modal
      v-model:open="aiAnalysisModalVisible"
      title="AI作业分析"
      width="800px"
      :footer="null"
    >
      <a-skeleton v-if="aiAnalyzing" active />
      <div v-else>
        <div v-if="aiSuggestions" class="suggestions-container">
          <a-card :title="aiSuggestions.summaryTitle || '优化建议概览'" style="margin-bottom: 16px">
            <p>{{ aiSuggestions.summary }}</p>
          </a-card>

          <a-collapse v-model:activeKey="activeSuggestionKeys" accordion>
            <a-collapse-panel 
              v-if="aiSuggestions.difficulty.length > 0"
              key="difficulty" 
              header="难度分布建议"
            >
              <ul class="suggestion-list">
                <li v-for="(item, index) in aiSuggestions.difficulty" :key="'difficulty-'+index">
                  {{ item }}
                </li>
              </ul>
            </a-collapse-panel>
            
            <a-collapse-panel 
              v-if="aiSuggestions.types.length > 0"
              key="types" 
              header="题目类型建议"
            >
              <ul class="suggestion-list">
                <li v-for="(item, index) in aiSuggestions.types" :key="'types-'+index">
                  {{ item }}
                </li>
              </ul>
            </a-collapse-panel>
            
            <a-collapse-panel 
              v-if="aiSuggestions.knowledge.length > 0"
              key="knowledge" 
              header="知识点覆盖建议"
            >
              <ul class="suggestion-list">
                <li v-for="(item, index) in aiSuggestions.knowledge" :key="'knowledge-'+index">
                  {{ item }}
                </li>
              </ul>
            </a-collapse-panel>
            
            <a-collapse-panel 
              v-if="aiSuggestions.other.length > 0"
              key="other" 
              header="其他改进建议"
            >
              <ul class="suggestion-list">
                <li v-for="(item, index) in aiSuggestions.other" :key="'other-'+index">
                  {{ item }}
                </li>
              </ul>
            </a-collapse-panel>
          </a-collapse>
        </div>

        <div class="stats-panel">
          <div class="difficulty-analysis">
            <h4>难度分布</h4>
            <a-progress
              :percent="difficultyAnalysis.easy"
              :stroke-color="'#52c41a'"
              :format="() => `简单 ${difficultyAnalysis.easy}%`"
            />
            <a-progress
              :percent="difficultyAnalysis.medium"
              :stroke-color="'#faad14'"
              :format="() => `中等 ${difficultyAnalysis.medium}%`"
            />
            <a-progress
              :percent="difficultyAnalysis.hard"
              :stroke-color="'#f5222d'"
              :format="() => `困难 ${difficultyAnalysis.hard}%`"
            />
          </div>
          <a-divider />
          <h4>时间预估</h4>
          <p>预计平均完成时间: {{ timeEstimation }}分钟</p>
        </div>

        <div class="modal-actions" style="margin-top: 16px; text-align: right">
          <a-button @click="aiAnalysisModalVisible = false">取消</a-button>
          <a-button 
            type="primary" 
            @click="confirmAssignment"
            style="margin-left: 8px"
            :loading="assigning"
          >
            确认
          </a-button>
        </div>
      </div>
    </a-modal>

      <!-- Question Bank Panel -->
      <div class="question-bank">
        <a-row :gutter="16">
          <a-col
            v-for="question in filteredQuestions"
            :key="question.question_id"
            :span="8"
            style="margin-bottom: 16px"
          >
          <a-card
            class="question-card"
            :class="{ selected: isQuestionSelected(question.question_id) }"
            @click="showQuestionDetail(question)"
          >
            <template #extra>
              <a-checkbox
                :checked="isQuestionSelected(question.question_id)"
                @click.stop
                @change="(e) => {
                  e.stopPropagation();
                  toggleQuestionSelection(question.question_id);
                }"
              />
            </template>

            <div v-if="!expandedQuestions[question.question_id]" class="question-preview">
              <p><strong>题目：</strong>{{ truncateText(question.question_stem, 50) }}</p>
              <div class="question-meta">
                <a-tag :color="getDifficultyColor(question.difficulty_level)">
                  {{ getDifficultyName(question.difficulty_level) }}
                </a-tag>
                <span>阶段: {{ getPhaseName(question.phase) }}</span>
                <span>分值: {{ question.points || 5 }}分</span>
              </div>
            </div>

            <div v-else class="question-content">
              <p><strong>题目：</strong>{{ question.question_stem }}</p>
              <div v-if="question.options">
                <p><strong>选项：</strong></p>
                <ul>
                  <li v-for="(option, idx) in question.options" :key="idx">
                    {{ option }}
                  </li>
                </ul>
              </div>
              <p v-if="question.correct_answer"><strong>答案：</strong>{{ question.correct_answer }}</p>
              <div class="question-meta">
                <a-tag :color="getDifficultyColor(question.difficulty_level)">
                  {{ getDifficultyName(question.difficulty_level) }}
                </a-tag>
                <span>阶段: {{ getPhaseName(question.phase) }}</span>
                <span>分值: {{ question.points || 5 }}分</span>
              </div>
            </div>
          </a-card>
          </a-col>
        </a-row>
      </div>
    </div>

    <!-- 详细题目模态框 -->
    <a-modal
      v-model:open="questionDetailVisible"
      :title="题目详情"
      width="800px"
      :footer="null"
      :bodyStyle="{ padding: '24px' }"
    >
      <div v-if="currentQuestion" class="question-detail">
        <a-card :bordered="false">
          <div class="question-content">
            <h3>题目内容</h3>
            <p class="question-text">{{ currentQuestion.question_stem }}</p>
            
            <div v-if="currentQuestion.options" class="options-section">
              <h4>选项</h4>
              <ul class="options-list">
                <li v-for="(option, idx) in currentQuestion.options" :key="idx">
                  <span class="option-text">{{ option }}</span>
                </li>
              </ul>
            </div>

            <div v-if="currentQuestion.correct_answer" class="answer-section">
              <h4>参考答案</h4>
              <p class="answer-text">{{ currentQuestion.correct_answer }}</p>
            </div>
          </div>

          <a-divider />

          <div class="question-meta">
            <a-space :size="16">
              <a-tag :color="getDifficultyColor(currentQuestion.difficulty_level)">
                难度: {{ getDifficultyName(currentQuestion.difficulty_level) }}
              </a-tag>
              <a-tag color="blue">阶段: {{ getPhaseName(currentQuestion.phase) }}</a-tag>
              <a-tag color="orange">分值: {{ currentQuestion.points || 5 }}分</a-tag>
            </a-space>
          </div>
        </a-card>
      </div>
    </a-modal>

    <!-- Assignment Modal -->
    <a-modal
      v-model:open="assignmentModalVisible"
      title="布置作业"
      width="600px"
      @ok="assignHomework"
      :confirm-loading="assigning"
    >
      <a-form layout="vertical">
        <a-form-item label="作业标题" required>
          <a-input v-model:value="homeworkTitle" placeholder="例如：二次函数专项练习" />
        </a-form-item>
        <a-form-item label="截止时间" required>
          <a-date-picker
            v-model:value="deadline"
            show-time
            format="YYYY-MM-DD HH:mm"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="适用班级">
          <a-select
            v-model:value="selectedClasses"
            mode="multiple"
            placeholder="选择班级"
            style="width: 100%"
          >
            <a-select-option
              v-for="cls in classList"
              :key="cls.id"
              :value="cls.id"
            >
              {{ cls.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-divider />
        <h4>已选题目 ({{ selectedQuestions.length }})</h4>
        <a-list
          :data-source="selectedQuestions"
          :grid="{ gutter: 16, column: 1 }"
        >
          <template #renderItem="{ item }">
            <a-list-item>
              <a-card>
                <p>{{ item.question_stem }}</p>
                <p class="question-meta">
                  难度: {{ getDifficultyName(item.difficulty_level) }} |
                  分值: {{ item.points || 5 }}分
                </p>
              </a-card>
            </a-list-item>
          </template>
        </a-list>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import axios from 'axios';

const phaseMap = {
  1: '准备阶段',
  2: '认知阶段',
  3: '理解阶段',
  4: '应用阶段',
  5: '巩固阶段',
  6: '评估阶段',
  7: '创新迁移阶段'
};

export default {
  name: 'HomeworkAssignment',
  data() {
    return {
      phaseMap: {
        1: '准备阶段',
        2: '认知阶段',
        3: '理解阶段',
        4: '应用阶段',
        5: '巩固阶段',
        6: '评估阶段',
        7: '创新迁移阶段'
      },
      expandedQuestions: {},
      filter: {
      phase: null,
      chapter: null,
      knowledgePoint: '',
      questionType: null
    },
    questionTypes: [
      { value: 'choice', label: '选择题' },
      { value: 'text', label: '文本题' }
    ],
      currentQuestion: null,
      questionDetailVisible: false,
      chapterList: [],
      chapterLoading: false,
      questionList: [],
      questionLoading: false,
      selectedQuestions: [],
      assignmentModalVisible: false,
      homeworkTitle: '',
      deadline: null,
      selectedClasses: [],
      classList: [
        { id: 'class1', name: '高一(1)班' },
        { id: 'class2', name: '高一(2)班' },
        { id: 'class3', name: '高一(3)班' },
      ],
      aiAnalysisModalVisible: false,
      aiAnalyzing: false,
      aiSuggestions: null,
      activeSuggestionKeys: ['difficulty'],
      difficultyAnalysis: {
        easy: 0,
        medium: 0,
        hard: 0
      },
      timeEstimation: 0,
      apiConfig: {
        baseUrl: 'http://localhost:8000',
        apiUrl:'http://121.40.242.43/v1',
        endpoints: {
          updates: '/api/updates/'
    }
      },
      
      aiApiKeys: {
        optimization: null,
        generation: null
      },
    apiKeyLoading: false
    }
  },
  created() {
    this.fetchAllChapters();
    this.fetchAllQuestions();
    this.fetchApiKeys();
  },
  computed: {
    filteredQuestions() {
      return this.questionList.filter(question => {
        const phaseMatch = !this.filter.phase || question.phase === this.filter.phase;
        const chapterMatch = !this.filter.chapter || question.chapter === this.filter.chapter;
        const knowledgeMatch = !this.filter.knowledgePoint ||
          (question.knowledge_points?.toLowerCase().includes(this.filter.knowledgePoint.toLowerCase()));
        const typeMatch = !this.filter.questionType || 
          (question.tags && question.tags.type === this.filter.questionType);
        return phaseMatch && chapterMatch && knowledgeMatch && typeMatch;
      });
    }
  },
  watch: {
    selectedQuestions: {
      handler(newVal) {
        if (newVal.length > 0) {
          this.analyzeSelectedQuestions();
        }
    },
      deep: true
    }
    },
  methods: {
    noop() {},
    async fetchApiKeys() {
      this.apiKeyLoading = true;
      try {
        const response = await axios.get('http://127.0.0.1:8000/api/knowledge-base-keys/');
        if (response.status === 200 && response.data) {
          const keys = response.data;
          this.aiApiKeys.optimization = keys.find(k => k.name === '题目优化助手')?.api_key || null;
          this.aiApiKeys.generation = keys.find(k => k.name === '题目一键生成助手')?.api_key || null;
        }
        console.log(this.aiApiKeys); 
      } catch (error) {
        console.error('Failed to fetch API keys:', error);
      } finally {
        this.apiKeyLoading = false;
      }
    },
    async fetchAllChapters() {
      this.chapterLoading = true;
      try {
        const response = await axios.get('http://127.0.0.1:8000/api/chapters/');
        if (response.status === 200 && response.data) {
        this.chapterList = response.data;
      } else {
          throw new Error('Invalid response');
      }
      } catch (error) {
        console.error('Chapter fetch error:', error);
        this.$message.error('获取章节失败: ' + (error.response?.data?.message || error.message));
        this.chapterList = [];
      } finally {
        this.chapterLoading = false;
      }
    },
    async fetchAllQuestions() {
      this.questionLoading = true;
      try {
        const response = await axios.get('http://127.0.0.1:8000/api/question-lists/');
        if (response.status === 200 && response.data) {
          this.questionList = JSON.parse(JSON.stringify(response.data));
        } else {
          throw new Error('Invalid response');
        }
      } catch (error) {
        console.error('Question fetch error:', error);
        this.$message.error('获取题目失败: ' + (error.response?.data?.message || error.message));
        this.questionList = [];
      } finally {
        this.questionLoading = false;
      }
    },
    toggleQuestionExpansion(questionId) {
      this.expandedQuestions = {
        ...this.expandedQuestions,
        [questionId]: !this.expandedQuestions[questionId]
      };
    },
    showQuestionDetail(question) {
    this.currentQuestion = question;
    this.questionDetailVisible = true;
  },
    truncateText(text, length) {
      return text.length > length ? text.substring(0, length) + '...' : text;
    },
    toggleQuestionSelection(questionId) {
      if (!Array.isArray(this.selectedQuestions)) {
        this.selectedQuestions = [];
      }
      const question = this.questionList.find(q => q.question_id === questionId);
      if (!question) return;

      const index = this.selectedQuestions.findIndex(q => q?.question_id === questionId);
      if (index >= 0) {
        this.selectedQuestions = this.selectedQuestions.filter(q => q.question_id !== questionId);
      } else {
        this.selectedQuestions = [...this.selectedQuestions, {...question}];
      }
    },

    isQuestionSelected(questionId) {
      return this.selectedQuestions.some(q => q.question_id === questionId);
    },
    async showAssignmentModal() {
      if (this.selectedQuestions.length === 0) {
        this.$message.warning('请至少选择一道题目');
        return;
      }
      this.showAIAnalysisModal();
    },

    async showAIAnalysisModal() {
      this.aiAnalysisModalVisible = true;
      this.aiAnalyzing = true;
      
      try {
        await this.getAISuggestions();
      } finally {
        this.aiAnalyzing = false;
      }
    },
    async confirmAssignment() {
      this.aiAnalysisModalVisible = false;
      this.assignmentModalVisible = true;
    },

    async recordUpdate(action, target, details = '') {
      try {
        const message = `${action === 'add' ? '添加' : action === 'delete' ? '删除' : '更新'}了${target}: ${details}`;
        await axios.post(this.apiConfig.baseUrl + this.apiConfig.endpoints.updates, {
          message,
        });
      } catch (error) {
        console.error('记录更新日志失败:', error);
      }
    },
    async getAISuggestions() {
      if (!this.aiApiKeys.optimization) {
        this.$message.error('题目优化助手API Key未配置');
        return;
      }
      const difficulties = this.selectedQuestions.map(q => q.difficulty_level);
      const total = difficulties.length;
      
      this.difficultyAnalysis = {
        easy: Math.round((difficulties.filter(d => d === 1).length / total) * 100),
        medium: Math.round((difficulties.filter(d => d === 2).length / total) * 100),
        hard: Math.round((difficulties.filter(d => d === 3).length / total) * 100)
      };

      this.timeEstimation = this.selectedQuestions.reduce((sum, q) => {
        if (q.difficulty_level === 1) return sum + 2;
        if (q.difficulty_level === 2) return sum + 5;
        return sum + 8;
      }, 0);

      try {
        const prompt = `请分析以下作业并给出优化建议：
作业标题: ${this.homeworkTitle}
题目数量: ${this.selectedQuestions.length}题
难度分布: 简单${this.difficultyAnalysis.easy}% 中等${this.difficultyAnalysis.medium}% 困难${this.difficultyAnalysis.hard}%

题目列表:
${this.selectedQuestions.map((q, i) => 
  `${i+1}. ${q.question_stem} (${q.points || 5}分, ${this.getDifficultyName(q.difficulty_level)})`
).join('\n')}

请从以下方面给出具体建议:
1. 难度分布是否合理
2. 题目类型搭配是否恰当
3. 知识点覆盖是否全面
4. 其他改进建议`;

        const response = await fetch(this.apiConfig.apiUrl +'/chat-messages', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${this.aiApiKeys.optimization}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            inputs: {},
            query: prompt,
            response_mode: "blocking",
            user: "teacher-assistant"
          })
        });

        const data = await response.json();
        this.aiSuggestions = this.parseAISuggestions(data.answer || '');
      } catch (error) {
        console.error('获取AI建议失败:', error);
        this.aiSuggestions = {
          summary: '获取AI建议失败，请稍后再试',
          difficulty: [],
          types: [],
          knowledge: [],
          other: []
        };
      }
    },

    parseAISuggestions(text) {
      const result = {
        summaryTitle: '优化建议概览',
        summary: '',
        difficulty: [],
        types: [],
        knowledge: [],
        other: []
      };
      
      text = text.replace(/\*\*/g, '').replace(/^根据您提供的作业信息，以下是我的优化建议：\s*/, '');
      
      const summaryEnd = text.search(/\n\s*1\./);
      result.summary = summaryEnd > 0 ? text.substring(0, summaryEnd).trim() : text;
      
      const extractItems = (sectionText) => {
        return sectionText.split('\n')
          .map(line => line.replace(/^[-\d.]+\s*/, '').trim())
          .filter(line => line.length > 0 && !line.startsWith('建议增加') && !line.startsWith('可以考虑'));
      };
      
      const sections = text.split(/\n\s*\d+\./).slice(1);
      
      if (sections.length >= 1) {
        result.difficulty = extractItems(sections[0]);
      }
      if (sections.length >= 2) {
        result.types = extractItems(sections[1]);
      }
      if (sections.length >= 3) {
        result.knowledge = extractItems(sections[2]);
      }
      if (sections.length >= 4) {
        result.other = extractItems(sections[3]);
      }
      
      return result;
    },

    analyzeSelectedQuestions() {
      this.aiAnalyzing = true;

      const difficulties = this.selectedQuestions.map(q => q.difficulty_level);
      const total = difficulties.length;

      this.difficultyAnalysis = {
        easy: Math.round((difficulties.filter(d => d === 1).length / total) * 100),
        medium: Math.round((difficulties.filter(d => d === 2).length / total) * 100),
        hard: Math.round((difficulties.filter(d => d === 3).length / total) * 100)
      };

      this.timeEstimation = this.selectedQuestions.reduce((sum, q) => {
        if (q.difficulty_level === 1) return sum + 2;
        if (q.difficulty_level === 2) return sum + 5;
        return sum + 8;
      }, 0);

      this.aiAnalyzing = false;
    },
    async assignHomework() {
      if (!this.homeworkTitle) {
        this.$message.error('请输入作业标题');
        return;
      }
      if (!this.deadline) {
        this.$message.error('请设置截止时间');
        return;
      }

      this.assigning = true;
      try {
        const knowledgePoints = [...new Set(
          this.selectedQuestions.flatMap(q => q.tags?.knowledgePoints?.split(',') || [])
        )].join(',');

        // 1. 创建作业
        const homeworkRes = await axios.post('http://127.0.0.1:8000/api/homework/', {
          title: this.homeworkTitle,
          deadline: this.deadline.toISOString(),  // 使用标准ISO格式
          knowledge_points: this.selectedQuestions
            .flatMap(q => q.tags?.knowledgePoints || [])
            .join(','),
          questions: this.selectedQuestions.map(q => q.question_id)  // 直接传入题目ID数组
        });
        await this.recordUpdate(
          'add',
          '作业',
          `题目: ${this.selectedQuestions.length}题, ` +
          `知识点: ${knowledgePoints || '未指定'}`
        );

        this.$message.success('作业布置成功');
        this.resetForm();
      } catch (error) {
        console.error('布置作业失败:', error.response?.data || error);
        this.$message.error(`布置作业失败: ${error.response?.data?.detail || error.message}`);
      } finally {
        this.assigning = false;
        this.assignmentModalVisible = false;
      }
    },
    resetForm() {
      this.selectedQuestions = [];
      this.homeworkTitle = '';
      this.deadline = null;
      this.selectedClasses = [];
    },
    getDifficultyName(difficulty) {
      const map = {
        1: '简单',
        2: '中等',
        3: '困难'
      };
      return map[difficulty] || difficulty;
    },
    getPhaseName(phase) {
      return phaseMap[phase] || phase;
    },
    getDifficultyColor(difficulty) {
      const map = {
        1: 'green',
        2: 'orange',
        3: 'red'
      };
      return map[difficulty] || 'blue';
    }
  }
}
</script>

<style scoped>
.assignment-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.question-bank {
  background: #fafafa;
  border-radius: 8px;
  padding: 16px;
  min-height: 500px;
}

.question-card {
  height: 100%;
  cursor: pointer;
  transition: all 0.3s;
}

.question-card.selected {
  border-color: #1890ff;
  background-color: #f0f9ff;
}

.question-content {
  margin-bottom: 12px;
}

.question-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
  font-size: 0.85em;
  color: #666;
}

.ai-analysis-section {
  margin-top: 16px;
}

.stats-panel {
  padding: 16px;
}

.difficulty-analysis {
  margin: 16px 0;
}

.difficulty-analysis .ant-progress {
  margin-bottom: 8px;
}

.question-preview {
  cursor: pointer;
}

.question-content {
  cursor: pointer;
  margin-bottom: 12px;
}
.question-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.question-content {
  margin-bottom: 16px;
}

.question-text {
  font-size: 16px;
  line-height: 1.6;
  white-space: pre-wrap;
}

.options-section {
  margin-top: 16px;
}

.options-list {
  list-style: none;
  padding: 0;
}

.options-list li {
  margin-bottom: 8px;
  display: flex;
  align-items: baseline;
}

.option-label {
  font-weight: bold;
  margin-right: 8px;
  min-width: 20px;
}

.answer-section {
  margin-top: 16px;
  padding: 12px;
  background: #f6f6f6;
  border-radius: 4px;
}

.answer-text {
  font-weight: 500;
  color: #1890ff;
}
</style>




